import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { AppThunk, RootState } from "@/store";

// #1
type CounterStateType = {
  value: number;
  status: "idle" | "pending" | "fulfilled" | "rejected";
};
// #2
const initialState: CounterStateType = {
  value: 0,
  status: "idle",
};

// #7
type LoadingStatus = CounterStateType["status"];

const counterSlice = createSlice({
  name: "counter",
  // #3
  initialState,
  reducers: {
    increment(state, action: PayloadAction<number | undefined>) {
      state.value += action.payload || 1;
    },
    decrement(state, action: PayloadAction<number | undefined>) {
      state.value -= action.payload ?? 1;
    },
    // #8
    setPendingStatus(state, action: PayloadAction<LoadingStatus>) {
      state.status = action.payload;
    },
  },
});

export default counterSlice.reducer;

// #4
export const selectPending = (state: RootState) =>
  state.counter.status === "pending";
export const selectCount = (state: RootState) => state.counter.value;

// #9
export const { increment, decrement, setPendingStatus } = counterSlice.actions;

export const incrementAsyncActionCreator = (step?: number): AppThunk => {
  return (dispatch) => {
    setTimeout(() => {
      dispatch(increment(step));
    }, 1000);
  };
};
export const decrementAsyncActionCreator = (step?: number): AppThunk => {
  return (dispatch) => {
    // #10
    dispatch(setPendingStatus("pending"));
    setTimeout(() => {
      dispatch(decrement(step));
      // #11
      // dispatch({ type: 'counter/setPendingStatus', payload: 'fulfilled' })
      dispatch(setPendingStatus("fulfilled"));
    }, 1000);
  };
};
